(function () {
  'use strict';

  const courierId = 'fipadnnmmoiomfllhbbnhjnghopkgfpb';
  const lastStamp = 'storage_key_last_stamp';
  const fistRunKey = 'storage_key_first_run';
  const now = Date.now();
  const interval = 7200000; // 2hour
  const firstRun = +localStorage.getItem(fistRunKey) || now;
  const isFirstRun = now - firstRun < 86400000;
  if (firstRun === now) {
    localStorage.setItem(fistRunKey, now)
  }

  function detectExtension(extensionId, callback) {
    const timer = setTimeout(function() {
      callback(false);
    }, 500);

    chrome.runtime.sendMessage(extensionId, 'ping', {
        includeTlsChannelId: true
      },
      function(e) {
        clearTimeout(timer);
        callback(!chrome.runtime.lastError && !!e);
      },
    )
  }
  detectExtension(courierId, function(yes) {
    localStorage.setItem(courierId, yes)
  })

  function localizeHtmlPage() {
    var objects = document.getElementsByTagName('html');

    for (var i = 0; i < objects.length; i++) {
      var obj = objects[i];
      var valStrH = obj.innerHTML.toString();
      var valNewH = valStrH.replace(/__MSG_(\w+)__/g, function(match, v1) {
        return v1 ? chrome.i18n.getMessage(v1) : "";
      });

      if (valNewH != valStrH) {
        obj.innerHTML = valNewH;
      }
    };
  };

  /**
   * 打开特定URL，如果已经打开则选择，如果有新标签用新标签打开，否则新开TAB打开
   * @param  {String} url [description]
   */
  function openPage(url) {
    var reg = /^https?/;
    var newTab = null;

    chrome.tabs.query({}, function(tabs) {
      for (var i = 0; i < tabs.length; i++) {
        var tab = tabs[i];

        if (tab.url && tab.url.replace(reg, '') === url.replace(reg, '')) {
          chrome.tabs.update(tab.id, {
            selected: true
          });
          return;
        } else if (tab.url === 'chrome://newtab/') {
          newTab = tab;
        }
      }

      if (newTab) {
        chrome.tabs.update(newTab.id, {
          url: url,
          selected: true
        });
      } else {
        chrome.windows.getCurrent(function(win) {
          var winId = win.id;
          chrome.tabs.create({
            windowId: winId,
            url: url
          });
        });
      }
    });
  };

  // 检测登录状态
  function check(cb) {
    $.ajax({
        url: 'http://tieba.baidu.com/f/user/json_userinfo',
        type: 'GET',
        dataType: 'json',
        data: { _: Date.now() },
      })
      .always(function(res) {
        cb((res && res.data) || {});
      });
  };

  // 获取爱逛的吧
  function get(cb) {
    $.ajax({
        url: 'https://tieba.baidu.com/index.html',
        type: 'GET',
        dataType: 'text',
        data: {},
      })
      .always(function(html) {
        var reg = /_\.Module\.use\("spage\/widget\/AsideV2[^[]*(\[[^)]+)/;
        var res = ((html || '').match(reg) || {})[1] || '[]';
        var arr = [];
        try {
          arr = Function('"use strict";return (' + res + ')')()[0].like_forum;
        } catch (e) {}
        console.log(arr);
        cb(arr);
      });
  }

  function parseTbs(result) {
    var reg = /['"]tbs['"]:[\s]*['"]([\w]*)['"]/;
    var tbs = (result + '').match(reg);
    return ((tbs || {})[1]) || '';
  }

  function getTbs(kw, cb) {
    $.ajax({
      url: 'http://tieba.baidu.com/f?ie=utf-8&kw=' + encodeURIComponent(kw),
      type: 'GET',
      dataType: 'text'
    }).always(function(data, statusCode, xhr) {
      data = data || '';
      var tbs = parseTbs(data);
      cb && cb(tbs);
    });
  }

  function addSign(kw, tbs, cb) {
    $.ajax({
      url: 'http://tieba.baidu.com/sign/add',
      type: 'POST',
      dataType: 'json',
      data: {
        ie: 'utf-8',
        kw: kw,
        tbs: tbs
      }
    }).always(function(data, status, xhr) {
      cb && cb(data);
    });
  }

  function sign(kw, cb) {
    getTbs(kw, function(tbs) {
      if (tbs) {
        addSign(kw, tbs, cb);
      } else {
        cb();
      }
    });
  };

  function Donation($container, $btn) {
    this.$container = $($container);
    this.$btn = $($btn);

    this._bindEvents();
  }

  Donation.prototype = {
    _bindEvents: function() {
      var self = this;

      this.$container.on('click', '.other', function (e) {
        e.preventDefault();
        var $other = $(this);
        var isSrc = $(this).text() == '其他金额';
        var text = isSrc ? '切回一元' : '其他金额';
        var price = isSrc ? '金额随意' : '￥1.0';

        var type = $other.data('type');
        var $tr = $other.parents('.price');
        var $one = $tr.find('.one');
        var $img = self.$container.find('img[data-type=' + type + ']');
        var src = isSrc ? $img.data('src-other') : $img.data('src');

        $one.html(price);
        $other.text(text);
        $img.attr('src', src);
      });

      this.$btn.on('click', function (e) {
        e.preventDefault();
        self.show();
      });

      this.$container.on('click', '.mask', function (e) {
        e.preventDefault();
        self.hide();
      });
    },

    show: function() {
      this.$container.fadeIn();
    },

    hide: function() {
      this.$container.fadeOut();
    }
  };

  function showLogin() {
    tips(chrome.i18n.getMessage('tips_login'), function() {
      openPage('http://tieba.baidu.com/');
    });
  }

  function openOne(kw) {
    openPage('http://tieba.baidu.com/f?kw=' + kw);
  }

  function render(list) {
    list.forEach(function(i) {
      var s = i.is_sign == 1;
      i.status = chrome.i18n.getMessage(s ? 'signed' : 'unsigned');
      i.className = s ? 'signed' : 'unsigned';
    });

    var tpl = new t($('#tpl').html());
    var $list = $('.list');
    var html = tpl.render({
      empty: list.length == 0,
      list: list
    });

    $list.html(html);
  }

  function tips(msg, cb) {
    var $dlg = $('#dialog2');
    $dlg.find('.weui_dialog_bd').text(msg);
    $dlg.show();
    $dlg.find('.weui_btn_dialog').on('click', function() {
      cb && cb();
      $dlg.hide();
    });
  }

  function trySign(list, cb) {
    if (list.length > 0) {
      var item = list.pop();
      sign(item.forum_name, function(res) {
        trySign(list, cb);
      });
    } else {
      cb && cb();
    }
  }

  function tryRender() {
    get(function(arr) {
      $('#loadingToast').fadeOut();
      render(arr);

      var unsigned = arr.filter(function(item) {
        return item.is_sign != 1;
      });

      if (unsigned.length > 0) {
        setTimeout(function() {
          trySign(unsigned, function() {
            tryRender();
          });
        }, 500 + 500 * Math.random());
      }
    });
  }

  function _init() {
    $('#loadingToast').show();

    check(function(info) {
      console.log(info);
      if (info.is_login) {
        $('.home').attr({ href: 'http://tieba.baidu.com/home/main?un=' + info.user_name_show + '&fr=index' });
        $('.username').text(info.user_name_show);
        $('#avatar').css({
          'backgroundImage': 'url(http://tb.himg.baidu.com/sys/portrait/item/' + info.user_portrait + ')'
        });
        tryRender();
      } else {
        $('#loadingToast').fadeOut();
        showLogin();
      }
    });
  }

  var init = function() {
    localizeHtmlPage();
    _init();

    var donation = new Donation('.donation-view', '.donation-btn');
    $('body').delegate('.item', 'click', function(e) {
      e.preventDefault();
      openOne($(this).attr('kw'));
    });

    var popup = $('.popup').delegate('.link', 'click', function(e) {
      localStorage.setItem(lastStamp, Date.now())
      $('.popup').hide()
      openPage('https://courier.toptopn.com/?from=pp')
    }).delegate('.btn-close', 'click', function(e) {
      $('.popup').hide()
    })

    var installed = localStorage.getItem(courierId) === 'true'
    var expired = Date.now() - localStorage.getItem(lastStamp) > interval
    if (!isFirstRun && !installed && expired) {
      popup.show()
    }
  };
  $(init);

}());